package com.shiqi.bio.broadcast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

/**
 * @author shiqi
 * @version 1.0.0
 * @ClassName ServerReaderThread.java
 * @Description
 * @createTime 2022-05-16
 */
public class ServerReaderThread extends Thread {

    private Socket socket;

    public ServerReaderThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try (BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
            String msg;
            //这里收到消息 再转发到其他端口，体现的就是端口转发的思想
            while ((msg = br.readLine()) != null) {
                sendMsgToAllClient(msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("当前socket下线");
            Server.allSocketOnLine.remove(socket);
        }
    }

    // 把当前客户端发来的消息推送给 所有在线的客户端
    private void sendMsgToAllClient(String msg) throws IOException {
        for (Socket sk : Server.allSocketOnLine) {
            PrintStream printStream = new PrintStream(sk.getOutputStream());
            printStream.println(msg);
            printStream.flush();
        }
    }

}
